<?php

class Model_Mapper_Log {

    protected $_dbTable;
    private static $instance;

    public static function newInstance() {
        if (!self::$instance instanceof self) {
            self::$instance = new self ();
        }
        return self::$instance;
    }

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Model_Table_Log');
        }
        return $this->_dbTable;
    }

    public function save(Model_Log $log) {
        $data = array('date' => $log->getDate(), 'section' => $log->getSection(), 'action' => $log->getAction(), 'data' => $log->getData(), 'ip' => $log->getIp(), 'who_id' => $log->getWho_id());
        $key = $this->getDbTable()->getPrimaryKey();
        $method = 'get' . ucfirst($key);
        $val = $categories->$method();
        if ($val == null) {
            unset($data [$key]);
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array($key . ' = ?' => $val));
        }
    }

    private function extend($args) {
        $items = array();
        foreach ($args as $arg) {
            $arg = $arg->toArray();
            $item = new Model_Log($arg);

            $items[] = $item;
        }
        return $items;
    }

    public function lastInsertID() {
        return $this->getDbTable()->getAdapter()->lastInsertId();
    }

    public function beginTransaction() {
        $this->getDbTable()->getAdapter()->beginTransaction();
    }

    public function commit() {
        $this->getDbTable()->getAdapter()->commit();
    }

    public function rollBack() {
        $this->getDbTable()->getAdapter()->rollBack();
    }

    public function getAll($enabled = false) {
        $table = $this->getDbTable();
        $select = $table->select();
        $select->from($this->getDbTable());
        if ($enabled) {
            $select->where('enabled=?', 1);
        }

        return $this->extend($table->fetchAll($select));
    }

    public function getByID($id) {
        if ($id == '') {
            throw new Exception('Invalid ID Provided.');
        }
        $table = $this->getDbTable();
        $select = $table->select();
        $select->where($this->getDbTable()->getPrimaryKey() . '=?', $id);
        $select->from($this->getDbTable());
        $result = $this->extend($table->fetchAll($select));
        return $result[0];
    }

}